package com.qijian.maindata.controller;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qijian.common.utils.DateUtils;
import com.qijian.common.utils.ObjectUtils;
import com.qijian.maindata.domain.EpmEqp;
import com.qijian.maindata.domain.excel.EpmEqpExcel;
import com.qijian.maindata.domain.query.EpmEqpQuery;
import com.qijian.maindata.service.IEpmEqpService;
import lombok.RequiredArgsConstructor;
import com.qijian.common.utils.mybatis.WhereEntityTool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import org.apache.http.util.Asserts;
import org.jetbrains.annotations.NotNull;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qijian.common.annotation.Log;
import com.qijian.common.annotation.PlugAnn;
import com.qijian.common.annotation.PlugParam;
import com.qijian.common.core.controller.BaseController;
import com.qijian.common.core.domain.AjaxResult;
import com.qijian.common.core.domain.entity.FlowableApproval;
import com.qijian.common.core.domain.entity.FlowableBack;
import com.qijian.common.enums.ApprovalDescriptionEnum;
import com.qijian.common.enums.BusinessType;
import com.qijian.common.exception.ServiceException;
import com.qijian.common.utils.SecurityUtils;
import com.qijian.common.utils.poi.ExcelUtil;
import com.qijian.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
/**
 * 设备Controller
 *
 * @author qijian
 * @date 2025-03-25
 */
@Api(tags = "设备")
@RestController
@RequiredArgsConstructor
@RequestMapping("/mainData/eqp")
public class EpmEqpController extends BaseController {

    private final IEpmEqpService epmEqpService;

    /**
     * 查询设备列表
     */
//    @PreAuthorize("@ss.hasPermi('business:eqp:list')")
    @GetMapping("/list")
    public TableDataInfo list(EpmEqpQuery query, Page<EpmEqp> page) {
        initOrderItem(EpmEqp.class, page.orders());
        return getDataTable(epmEqpService.page(page, WhereEntityTool.invoke(query)));
    }

    /**
     * 导出设备模版
     */
//    @PreAuthorize("@ss.hasPermi('business:eqp:export')")
    @Log(title = "设备" , businessType = BusinessType.EXPORT)
    @GetMapping("/exportTemplate")
    @SneakyThrows
    public AjaxResult exportTemplate(HttpServletResponse response) {
        return new ExcelUtil<>(EpmEqpExcel.class).importTemplateExcel("设备信息表");
    }

    /**
     * 导出设备列表模版
     */
//    @PreAuthorize("@ss.hasPermi('business:eqp:export')")
    @Log(title = "设备" , businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(EpmEqpQuery query, HttpServletResponse response) {
        new ExcelUtil<>(EpmEqp. class).exportExcel(response,epmEqpService.list( WhereEntityTool.invoke(query)), "设备数据");
    }
    /**
     * 导入设备表
     */
    @Log(title = "设备", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importData(MultipartFile file) throws Exception {
        Asserts.check(file != null && !file.isEmpty(), "文件为空，无法导入");
        List<EpmEqp> list = new ExcelUtil<>(EpmEqp.class).importExcel(file.getInputStream());
        return AjaxResult.success(epmEqpService.importList(list));
    }

    /**
     * 获取设备详细信息
     */
//    @PreAuthorize("@ss.hasAnyPermi('business:eqp:list,business:eqp:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(epmEqpService.getById(id));
    }

    /**
     * 新增设备
     */
//    @PreAuthorize("@ss.hasPermi('business:eqp:add')")
    @Log(title = "设备" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EpmEqp epmEqp) {
         getAjaxResult(epmEqp);
        return toAjax(epmEqpService.save(epmEqp));
    }


    private void getAjaxResult(EpmEqp epmEqp) {
        LambdaQueryWrapper<EpmEqp> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EpmEqp::getEqpCode, epmEqp.getEqpCode());
        if(epmEqp.getId()!=null){
        wrapper.ne(EpmEqp::getId, epmEqp.getId());
        }
        List<EpmEqp> list = epmEqpService.list(wrapper);
        if(list!=null && list.size()>0){
            throw new ServiceException("物料编码已存在！");
        }
    }

    /**
     * 修改设备
     */
//    @PreAuthorize("@ss.hasPermi('business:eqp:edit')")
    @Log(title = "设备" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EpmEqp epmEqp) {
        approval(epmEqpService.getById(epmEqp.getId()));
        return toAjax(epmEqpService.updateById(epmEqp));
    }

    /**
     * 删除设备
     */
//    @PreAuthorize("@ss.hasPermi('business:eqp:remove')")
    @Log(title = "设备" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<String> ids) {
        ids.forEach(id -> approval(epmEqpService.getById(id)));
        return toAjax(epmEqpService.removeByIds(ids));
    }

    /**
     * 单据提交审核
     */
    @Log(title = "设备", businessType = BusinessType.APPROVAL)
    @PlugAnn(groupClass = FlowableApproval.Approval.class, params = {"'epmEqp'", "T(com.qijian.common.utils.SecurityUtils).getUserId()", "T(com.qijian.common.utils.SecurityUtils).getDeptId()", "T(com.qijian.common.utils.SecurityUtils).getNickName()"})
    @GetMapping(value = "/approval/{id}")
    public AjaxResult approval(@PlugParam @PathVariable("id") Long id) {
        approval(epmEqpService.getById(id));
        EpmEqp epmEqpChange = new EpmEqp();
        epmEqpChange.setId(id);
        epmEqpChange.setApprovalStatus(ApprovalDescriptionEnum.B);
        return AjaxResult.success(epmEqpService.updateById(epmEqpChange));
    }

    /**
     * 单据审核通过
     */
    @Log(title = "设备", businessType = BusinessType.APPROVAL)
    @PreAuthorize("@ss.hasPermi('business:eqp:approved')")
    @GetMapping(value = "/approved/{id}")
    public AjaxResult approved(@PathVariable("id") Long id) {
        EpmEqp info = epmEqpService.getById(id);
        if (ObjectUtils.isNull(id) || info.getApprovalStatus() == ApprovalDescriptionEnum.C) {
            throw new ServiceException("E01:单据已审核！");
        }
        EpmEqp epmEqpChange = new EpmEqp();
        epmEqpChange.setId(id);
        epmEqpChange.setApprovalStatus(ApprovalDescriptionEnum.C);
        epmEqpChange.setApprovalBy(SecurityUtils.getNickName());
        epmEqpChange.setApprovalTime(DateUtils.getNowDate());
        return AjaxResult.success(epmEqpService.updateById(epmEqpChange));
    }

    /**
     * 单据反审核
     */
    @Log(title = "设备", businessType = BusinessType.APPROVAL)
    @PreAuthorize("@ss.hasPermi('business:eqp:deApproval')")
    @PlugAnn(groupClass = FlowableBack.Approval.class, params = {"'epmEqp'"})
    @GetMapping(value = "/deApproval/{id}")
    public AjaxResult deApproval(@PathVariable("id") Long id) {
        EpmEqp epmEqpChange = new EpmEqp();
        epmEqpChange.setId(id);
        epmEqpChange.setApprovalStatus(ApprovalDescriptionEnum.D);
        return AjaxResult.success(epmEqpService.updateById(epmEqpChange));
    }
}
